<template>
  <div>
    <el-card>
      <el-page-header icon="" title="用户管理">
        <template #content>
          <span class="text-large font-600 mr-3" style="font-size: 16px">
            添加用户
          </span>
        </template>
      </el-page-header>
      <el-form
        ref="userFormRef"
        style="max-width: 600px"
        :model="userForm"
        :rules="userFormRules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="userForm.user_name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="is_admin">
          <el-select
            v-model="userForm.is_admin"
            placeholder="Select"
            style="width: 100%"
          >
            <el-option label="管理员" :value="true"></el-option>
            <el-option label="编辑" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input v-model="userForm.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <Upload :avatar="userForm.avatar" @uploadChange="handleChange" />
        </el-form-item>
        <el-form-item class="button-container">
          <el-button type="primary" @click="submitForm()" class="custom-button">
            添加用户
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import Upload from "@/components/upload/Upload.vue";
import upload from "@/util/upload";
import { useRouter } from "vue-router";
const userFormRef = ref();
const userForm = reactive({
  user_name: "",
  password: "",
  is_admin: false, //编辑
  introduction: "",
  avatar: "",
  file: null,
  gender: 0, /////////////
});

const userFormRules = reactive({
  user_name: [{ required: true, message: "请输入名字", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  introduction: [
    { required: true, message: "请输入个人介绍", trigger: "blur" },
  ],
  avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
  is_admin: [{ required: true, message: "请选择权限", trigger: "blur" }],
});

//每次选择完图片之后的回调
const handleChange = (file) => {
  userForm.avatar = URL.createObjectURL(file);
  userForm.file = file; //把表单中放入原生的file对象
};

const router = useRouter();
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      //提交用户到后端
      await upload("/adminapi/user/add", userForm);
    }
  });
};
</script>

<style scoped>
.demo-ruleForm {
  margin-top: 50px;
}
</style>
